package utils

import (
	"encoding/json"
	"github.com/fwhezfwhez/errorx"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"time"
)

var validate *validator.Validate

func init() {
	validate = validator.New()
	_ = validate.RegisterValidation("timeAfterNow", timeCompare)
}

func GetStructByParams[T any](c *gin.Context) (*T, error) {
	obj := new(T)
	_ = c.ShouldBindJSON(obj)
	jsonS, _ := json.Marshal(obj)
	c.Set("requestData", jsonS)
	err := validate.Struct(obj)
	if err != nil {
		validationErrors := err.(validator.ValidationErrors)
		return nil, errorx.Wrap(validationErrors)
	}

	return obj, nil
}

func timeCompare(fl validator.FieldLevel) bool {
	timeStr := fl.Field().String()
	t, err := time.Parse(time.DateTime, timeStr)
	if err != nil {
		// 时间格式错误，返回校验不通过
		return false
	}
	now := time.Now()
	if t.After(now) {
		// 时间比当前时间晚，返回校验通过
		return true
	}
	// 时间比当前时间早或相等，返回校验不通过
	return false
}
